package com.sinog.biz.service.business.impl;

import com.sinog.biz.BizApplication;
import com.sinog.biz.config.ThreadPoolConfig;
import com.sinog.biz.mapper.havexml.SystemCodeMapper;
import com.sinog.biz.service.business.AddStatusStatisticsService;
import com.sinog.biz.util.CodeUrlUtils;
import com.sinog.core.model.XzzttjBean;
import com.sinog.core.util.DateUtil;
import com.sinog.core.util.JsonUtil;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * @desc 数据统计分析 - 添加状态统计 - AddStatusStatisticsServiceImpl
 * @author ybl
 * @date 2022/8/10
 */
@Slf4j
@Service
public class AddStatusStatisticsServiceImpl implements AddStatusStatisticsService {

    /**
     * 部级资源库
     */
    private JdbcTemplate bujiJdbcTemplate;
    /**
     * 自定义线程池
     */
    @Autowired
    private ThreadPoolConfig threadPoolConfig;
    /**
     * systemCodeMapper
     */
    @Autowired
    private SystemCodeMapper systemCodeMapper;

    /**
     * 数据统计分析 - 新增状态统计 - 查看 - 拿到所有的单位
     * @param param 参数集
     * @return Result
     */
    @Override
    public Result getUnit(String param) {
        //拿到传递的参数
        XzzttjBean xzzttjBean = JsonUtil.toBean(param,XzzttjBean.class);
        if(null == xzzttjBean.getProvince() || 0 >= xzzttjBean.getProvince().length()) {
            xzzttjBean.setProvince(CodeUrlUtils.getLocalCode());
        }
        String[] pstateType = xzzttjBean.getPstateType();
        //声明要返回的Map集合
        Map<String,Object> resultMap = new HashMap<>(16);
        // 数据源
        ApplicationContext applicationContext = BizApplication.applicationContext;
        bujiJdbcTemplate = (JdbcTemplate)applicationContext.getBean("bujiJdbcTemplate");
        String sql = "select " + "distinct dsc.adduserid, dsc.addusername " + "from data_statistics_contrast dsc " + "where" + " dsc.create_date >= '" + xzzttjBean.getBeginTime() + "'" + " and dsc.create_date <= '" + xzzttjBean.getEndTime() + "'" + " and dsc.province = '" + xzzttjBean.getProvince() + "'";
        if(pstateType != null && pstateType.length > 0) {
            StringBuilder pstateArray = new StringBuilder();
            for(String pstate : pstateType) {
                pstateArray.append(pstate).append(",");
            }
            sql += " and pstate in (" + pstateArray.substring(0,pstateArray.length() - 1) + ")";
        }
        if(null != xzzttjBean.getUnitId()) {
            sql += " and dsc.adduserid = '" + xzzttjBean.getUnitId() + "'";
        }
        log.info("获取所有单位执行的sql：" + sql);
        //查询所有待查询的监所id，name
        List<Map<String,Object>> idNameMapList = bujiJdbcTemplate.queryForList(sql);
        if(0 >= idNameMapList.size()) {
            resultMap.put("unit",null);
        } else {
            resultMap.put("unit",idNameMapList);
        }
        return Result.success(JsonUtil.toText(resultMap));
    }

    /**
     * 数据统计分析 - 添加状态统计 - 查看对应数据 - 拿到对应数据
     * @param param 参数集
     * @return Result
     */
    @Override
    public Result addStatusStatisticsData(String param) throws ParseException {
        Map<String,Object> returnData = new HashMap<>(16);
        //拿到传值
        XzzttjBean xzzttjBean = JsonUtil.toBean(param,XzzttjBean.class);
        //拿到省份
        if(null == xzzttjBean.getProvince() || 0 >= xzzttjBean.getProvince().length()) {
            xzzttjBean.setProvince(CodeUrlUtils.getLocalCode());
        }
        //拿到时间
        List<String> dateInterval = new ArrayList<>(16);
        if(Constants.Number.NUM_ONE == xzzttjBean.getDateType()) {
            //按天
            dateInterval = DateUtil.dateInterval(xzzttjBean.getBeginTime(),xzzttjBean.getEndTime());
        } else if(Constants.Number.NUM_TWO == xzzttjBean.getDateType()) {
            //按月
            dateInterval = DateUtil.dateIntervalMonth(xzzttjBean.getBeginTime(),xzzttjBean.getEndTime());
        }
        // 数据源
        ApplicationContext applicationContext = BizApplication.applicationContext;
        bujiJdbcTemplate = (JdbcTemplate)applicationContext.getBean("bujiJdbcTemplate");
        //异步遍历时间
        List<CompletableFuture<Integer>> collect = dateInterval.stream()
                                                               .map(day -> CompletableFuture.supplyAsync(new Supplier<Integer>() {
                                                                   @Override
                                                                   public Integer get() {
                                                                       String sql = "select sum(dsc.amount) as amount from data_statistics_contrast dsc where" + " dsc.province = '" + xzzttjBean.getProvince() + "'" + " and dsc.pstate = '" + xzzttjBean.getPstate() + "'" + " and dsc.adduserid = '" + xzzttjBean.getId() + "'";
                                                                       if (xzzttjBean.getDateType() == 1) {
                                                                           sql += " and to_days(dsc.create_date) = to_days('" + day + "')" + " group by date_format(dsc.create_date , \"%Y-%m-%d\")";
                                                                       } else if (Constants.Number.NUM_TWO == xzzttjBean.getDateType()) {
                                                                           sql += " and date_format(dsc.create_date , \"%Y-%m\") = '" + day + "'" + " group by date_format(dsc.create_date , \"%Y-%m\")";
                                                                       }
                                                                       int count;
                                                                       try {
                                                                           count = bujiJdbcTemplate.queryForObject(sql, int.class);
                                                                       } catch (EmptyResultDataAccessException e) {
                                                                           return 0;
                                                                       }
                                                                       return count;
                                                                   }
                                                               },threadPoolConfig.taskExecutor()))
                                                               .collect(Collectors.toList());
        returnData.put("amount",collect.stream().map(CompletableFuture::join).collect(Collectors.toList()));
        returnData.put("date",dateInterval);
        returnData.put("id",xzzttjBean.getId());
        return Result.success(JsonUtil.toText(returnData));
    }

    /**
     * 数据统计分析 - 添加状态统计 - 数据状态查看分析 - 拿到对应数据
     * @param pageIndex pageIndex
     * @param pageSize pageSize
     * @param param 参数集
     * @return Result
     */
    @Override
    public String getResultData(Integer pageIndex,Integer pageSize,String param) {
        Map<String,Object> returnData = new HashMap<>(16);
        //拿到传值
        XzzttjBean xzzttjBean = JsonUtil.toBean(param,XzzttjBean.class);
        //要循环的数组
        String[] pstateTypeArray = xzzttjBean.getPstateType();
        //省
        String province = xzzttjBean.getProvince();
        // 数据源
        ApplicationContext applicationContext = BizApplication.applicationContext;
        bujiJdbcTemplate = (JdbcTemplate)applicationContext.getBean("bujiJdbcTemplate");
        //拼接sql
        StringBuilder sql = new StringBuilder("select ");
        for(String item : pstateTypeArray) {
            sql.append("sum(case when pstate='").append(item).append("' then amount else 0 end ) as 'amount")
               .append(item).append("', ");
        }
        if(province != null && province.length() > 0) {
            sql.append("dsc.addusername as name ");
        } else {
            sql.append("dsc.province as name ");
        }
        sql.append("from data_statistics_contrast dsc " + "where " + "dsc.create_date >= '")
           .append(xzzttjBean.getBeginTime()).append("' and dsc.create_date <= '").append(xzzttjBean.getEndTime())
           .append("' ");
        if(xzzttjBean.getUnitId() != null) {
            sql.append("and dsc.adduserid = '").append(xzzttjBean.getUnitId()).append("'");
        }
        if(province != null && province.length() > 0) {
            StringBuilder sqlPstate = new StringBuilder();
            for(String item : pstateTypeArray) {
                sqlPstate.append(item).append(",");
            }
            sql.append("and dsc.pstate in (").append(sqlPstate.substring(0,sqlPstate.length() - 1))
               .append(") and dsc.province = '").append(province).append("' group by dsc.adduserid  ");
        } else {
            sql.append("group by dsc.province ");
        }
        //获取总条数与总页数
        String getPageSql = "select count(1) as `totalNumber` from (" + sql + ") as main";
        log.info("获取总数SQL：" + getPageSql);
        returnData.put("total",bujiJdbcTemplate.queryForObject(getPageSql,Long.class));
        if(xzzttjBean.getSortField() != null && xzzttjBean.getSortOrder() != null) {
            sql.append("order by ").append(xzzttjBean.getSortField()).append(" ").append(xzzttjBean.getSortOrder());
        }
        sql.append(" limit ").append(pageIndex * pageSize).append(", ").append(pageSize);
        log.info("获取值SQL：" + sql);
        returnData.put("data",bujiJdbcTemplate.queryForList(sql.toString()));
        return JsonUtil.toText(returnData);
    }

    /**
     * 数据统计分析 - 添加状态统计 - 数据状态查看分析 - 查询当前有的新增种类父级
     * @return Result
     */
    @Override
    public List<Map<String,Object>> getPstateList() {
        // 数据源
        ApplicationContext applicationContext = BizApplication.applicationContext;
        bujiJdbcTemplate = (JdbcTemplate)applicationContext.getBean("bujiJdbcTemplate");
        String sql = "SELECT dsc.pstate AS `key`, tc.code_name AS `value` FROM ( " + "SELECT DISTINCT pstate FROM data_statistics_contrast dsc " + "WHERE dsc.create_date > DATE_SUB(CURDATE(), INTERVAL 1 YEAR) " + ") AS dsc " + "LEFT JOIN ( " + "SELECT code_id, code_name, sn FROM tbsys_code tc WHERE tc.code_type = '10_1' " + ") AS tc ON dsc.pstate = tc.code_id " + "ORDER BY tc.sn";
        return bujiJdbcTemplate.queryForList(sql);
    }

    /**
     * 数据统计分析 - 添加状态统计 - 数据状态查看分析 - 查询当前子集的新增种类
     * @return Result
     */
    @Override
    public List<Map<String,Object>> getPstateAllList() {
        // 数据源
        ApplicationContext applicationContext = BizApplication.applicationContext;
        bujiJdbcTemplate = (JdbcTemplate)applicationContext.getBean("bujiJdbcTemplate");
        String sql = "SELECT code_name AS `name`, code_describe AS `width` FROM tbsys_code tc WHERE tc.code_type = '10_1' ORDER BY sn";
        return bujiJdbcTemplate.queryForList(sql);
    }

    /**
     * 数据统计分析 - 添加状态统计 - 数据状态查看分析 - 查查询所有的省份种类
     * @return Result
     */
    @Override
    public List<Map<String,String>> getProvince() {
        List<Map<String,String>> list = systemCodeMapper.getProvinceAll();
        return list;
    }

    /**
     * 数据统计分析 - 添加状态统计 - 数据状态查看分析 - 查询当前省
     * @return String
     */
    @Override
    public String getCurrentProvince() {
        return CodeUrlUtils.getLocalCode();
    }

    /**
     * 数据统计分析 - 添加状态统计 - 数据状态查看分析 - 获得所有状态
     * @return List<Map<String,Object>>
     */
    @Override
    public List<Map<String,Object>> getSort() {
        // 数据源
        ApplicationContext applicationContext = BizApplication.applicationContext;
        bujiJdbcTemplate = (JdbcTemplate)applicationContext.getBean("bujiJdbcTemplate");
        String sql = "SELECT DISTINCT tc.pcode_id AS `key`, tc.code_describe AS `value` FROM tbsys_code tc WHERE tc.code_type = '10_1' ORDER BY tc.sn";
        return bujiJdbcTemplate.queryForList(sql);
    }

    /**
     * 数据统计分析 - 添加状态统计 - 数据状态查看分析 - 获得状态内细节状态
     * @param id 状态父级分类id
     * @return List<Map<String,Object>>
     */
    @Override
    public List<Map<String,Object>> getSortDetails(String id) {
        // 数据源
        ApplicationContext applicationContext = BizApplication.applicationContext;
        bujiJdbcTemplate = (JdbcTemplate)applicationContext.getBean("bujiJdbcTemplate");
        String sql;
        if("".equals(id)) {
            sql = "SELECT tc.code_id AS id, code_name AS name FROM tbsys_code tc WHERE tc.code_type = '10_1' ORDER BY tc.sn";
        } else {
            sql = "select tc.code_id as id, code_name as name from tbsys_code tc where tc.code_type = '10_1' and tc.pcode_id = '" + id + "' order by tc.sn";
        }
        return bujiJdbcTemplate.queryForList(sql);
    }

    /**
     * 数据统计分析 - 添加状态统计 - 数据状态查看分析 - 拿到统计的数据
     * @return List<Map<String,Object>>
     */
    @Override
    public List<Map<String,Object>> getTotalData() {
        // 数据源
        ApplicationContext applicationContext = BizApplication.applicationContext;
        bujiJdbcTemplate = (JdbcTemplate)applicationContext.getBean("bujiJdbcTemplate");
        String sql = "";
        return bujiJdbcTemplate.queryForList(sql);
    }
}